import { ResponseResult } from "@/entity/ResponseResult";
import { UmsLoginParam } from "@/entity/UmsLoginParam";
import UmsMember from "@/entity/UmsMember";
import { AxiosError, AxiosResponse } from "axios";
import httpClient from "./http-client";
import { db_members } from "@/database/member";
import store, { TOKEN_USER_ID } from "@/store";

export class AuthService {
    baseUrl = "/api/v1.0/portal/auth";
    public getVerifyCodeUrl() {
        return `/mock-data/file-storage/verify-code-7xv6.jpg?v=${new Date().getTime()}`;
        return `${this.baseUrl}/verify-code.jpg?v=${new Date().getTime()}`;
    }

    public async login(param: UmsLoginParam) {
        if (param.verifyCode != "7xv6") {
            throw new AxiosError("验证码错误");
        }
        const user = db_members.find(it => it.username == param.username && it.password == param.password);
        if (user == null) {
            throw new AxiosError("用户名或密码错误");
        }
        return Promise.resolve({
            "tokenHead": "Bearer ",
            "token": "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJtMSIsImNyZWF0ZWQiOjE2ODY0Njg1NDc3NTYsImV4cCI6MTY4NzA3MzM0N30.FtwTZRQ2j0HB0bG_tzYGknwBhyCDgXQeR-y8WBKCvFUP9Vl2VsUyhVLvTUe1e9pVTJ0T62muu8IEuvEICR472g",
            "user": user,
        });
        return httpClient.post(`${this.baseUrl}/login?username=${param.username}&password=${param.password}&verifycode=${param.verifyCode}`).then((res: AxiosResponse<ResponseResult<{ token: string; tokenHead: string }>>) => {
            if (res.data.data) {
                return Promise.resolve(res.data.data);
            } else {
                throw "no data";
            }
        });
    }

    public async logout() {
        return Promise.resolve({ "code": 200, "message": "操作成功", "data": null });
        const body = {};
        return httpClient.post(`${this.baseUrl}/logout`, body);
    }

    public async current() {
        const userId = Number(store.getters[TOKEN_USER_ID]);
        const member = db_members.find(it => it.id == userId);
        if (member == null) {
            throw new AxiosError();
        }
        return Promise.resolve(member);
        return httpClient.get(`${this.baseUrl}/current`).then((res: AxiosResponse<ResponseResult<UmsMember>>) => {
            if (res.data.data) {
                return Promise.resolve(res.data.data);
            } else {
                throw "no data";
            }
        });
    }
}

const instance = new AuthService();
export default instance;